<template>
    <div>
        <el-card class="article-select">
            <!--面包屑导航-->
            <div slot="header" class="clearfix">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>个人设置</el-breadcrumb-item>
                </el-breadcrumb>
            </div>

            <!--个人设置内容-->
            <el-row :gutter="20">
                <!--基本信息-->
                <el-col :span="14">
                    <el-form ref="form" :model="personalInfo" label-width="80px" :rules="rules">
                        <el-form-item label="编号">
                            {{personalInfo.id}}
                        </el-form-item>
                        <el-form-item label="账号">
                            {{personalInfo.account}}
                        </el-form-item>
                        <el-form-item label="媒体名称" prop="name">
                            <el-input v-model="personalInfo.name"></el-input>
                        </el-form-item>
                        <el-form-item label="媒体介绍" prop="msg">
                            <el-input type="textarea" v-model="personalInfo.msg"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="e_mail">
                            <el-input v-model="personalInfo.e_mail"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button
                                    type="primary"
                                    @click = "onUploadUser"
                                    :disabled = "saveDisabled">保存
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <!--头像-->
                <el-col
                        :span="4"
                        :offset="2"
                >
                    <!--用label标签将头像和文本和选择文件关联-->
                    <label class="avatar-box" for="file">
                        <el-avatar
                                shape="square"
                                :size="140"
                                fit="cover"
                                :src="personalInfo.avatar_url"
                                class="avatar-pic"
                        >
                        </el-avatar>
                        <p class="edit-text">点击修改头像</p>
                    </label>
                    <!--
                        1、通过input[type='file']来选择本地的文件
                        2、通过选择文件（注意：选择相同的文件时不会触发事件）触发事件
                        3、在事件中控制弹出框是否显示在界面上，同时获取选择的文件（这里是图片）的地址
                        4、在弹出框中创建img标签来显示获取到地址的图片
                    -->
                    <input
                            type="file"
                            id="file"
                            ref="file"
                            style="display: none"
                            @change="onFileChange"
                            :disabled='inputDisabled'
                    >
                </el-col>
            </el-row>

            <!--弹出框选择头像图片-->
            <el-dialog
                    title="选择图片上传"
                    :visible.sync="dialogVisible"
                    :append-to-body="true"
                    custom-class="dialog"
                    center
                    width="500px"
                    :close-on-click-modal="false"
                    @opened="onDialogOpened()"
            >
                <div class="preview-image-wrap">
                    <img :src="previewImg" class="preview-image" ref="img_preview">
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="onUploadImage" :disabled="sureDisabled">确 定</el-button>
                    <el-button @click="dialogVisible = false">取 消</el-button>
                </span>
            </el-dialog>

        </el-card>
    </div>
</template>

<script>
    import 'cropperjs/dist/cropper.css';
    import Cropper from 'cropperjs';
    import globalBus from "../../util/global-bus";

    export default {
        name: "setting",
        data() {
            return {
                personalInfo:{
                    id:null,
                    account:'',
                    password:'',
                    name:'',
                    msg:'',
                    avatar_url:null,
                    e_mail:''
                },
                dialogVisible:false, //弹出框的显示状态
                previewImg:'',
                cropper:null,
                inputDisabled:false, //input按钮是否禁用
                sureDisabled:false , //修改图片是否禁用
                saveDisabled:false,  //保存按钮是否禁用
                rules: {
                    name:[
                        { required: true, message: '用户昵称不能为空', trigger: 'blur' },
                        { min: 1, max: 7, message: '长度在 1 到 7 个字符', trigger: 'blur' }
                    ],
                    e_mail:[
                        { pattern: /^([a-zA-Z0-9]+[_|_|\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
                            message: '必须符合邮箱规范',
                            trigger: 'blur'
                        }
                    ]
                }
            }
        },
        created() {
            this.personalInfo = {...this.$store.state.serveMember}
        },
        methods: {
            //input的事件，选择本地图片后触发
            onFileChange(){
                //获取图片地址
                let file = this.$refs['file']
                /*console.log(this.$refs['file'].files[0]);*/
                let avatarImgURL = window.URL.createObjectURL(file.files[0])

                //绑定弹出框中img标签的图片地址
                this.previewImg = avatarImgURL

                //让弹出框显示
                this.dialogVisible = true

                //解决了选择相同文件input[type='file']的事件不触发问题
                this.$refs.file.value = ''
            },

            //在dialog完全打开后的回调方法中创建一个裁剪器
            onDialogOpened(){
                // 图片裁切器必须基于 img 进行初始化
                // 注意：img 必须是可见状态才能正常完成初始化
                //       因为我们这里要在对话框里面初始化裁切器
                //       所以务必要在对话框完全打开的状态去进行初始化。

                //1、获取图片的dom元素
                let img_preview = this.$refs['img_preview']

                //3、因为当图片更新的时候，裁剪器不会更新，所以需要重建裁剪器
                //   以下操作如果已经有裁剪器了，就将其更新
                if(this.cropper){
                    this.cropper.replace(this.previewImg, true)
                    return
                }

                //2、创建一个裁剪器，把需要裁剪的图片dom元素给裁剪器
                this.cropper = new Cropper(img_preview, {
                    aspectRatio: 1,
                    viewMode:1,
                    dragMode:'none',
                    autoCropArea:0.7,
                    cropBoxResizable:false
                });
            },

            //点击dialog中的确定后修改本地的头像数据
            onUploadImage(){
                this.sureDisabled = true//按钮禁用

                this.$confirm('确认修改头像?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.cropper.getCroppedCanvas().toBlob((file) => {
                        this.personalInfo.avatar_url = window.URL.createObjectURL(file)
                        this.$store.state.serveMember.avatar_url = this.personalInfo.avatar_url
                        globalBus.$emit('onUploadUserAvatar',this.personalInfo.avatar_url)
                    })
                    this.dialogVisible = false//点击确定后关闭dialog
                    this.sureDisabled = false //解除按钮禁用
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                }).catch(() => {
                    this.sureDisabled = false //解除按钮禁用
                    this.$message({
                        type: 'info',
                        message: '取消修改'
                    });
                })
            },

            //点击保存修改用户信息
            onUploadUser(){
                //表单验证
                this.$refs["form"].validate((valid)=>{
                    //验证失败，返回
                    if (!valid) {
                        return
                    }
                    // 验证通过，修改用户信息
                    this.UploadUser()
                })
            },
            UploadUser(){
                this.saveDisabled = true //禁用保存按钮

                //修改用户信息
                this.$confirm('确认修改用户信息?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$store.state.serveMember.name = this.personalInfo.name
                    this.$store.state.serveMember.msg = this.personalInfo.msg
                    this.$store.state.serveMember.e_mail = this.personalInfo.e_mail
                    this.$store.state.serveMember.avatar_url = this.personalInfo.avatar_url
                    globalBus.$emit('onUploadUserName',this.personalInfo.name)

                    this.saveDisabled = false //解除按钮禁用
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                }).catch(() => {
                    this.saveDisabled = false //解除按钮禁用
                    this.$message({
                        type: 'info',
                        message: '取消修改'
                    });
                })
            }

        }
    }
</script>

<style scoped lang="scss">
    .avatar-box{
        /*background: red;*/
        user-select: none;
        .avatar-pic{
            margin: 0;
        }
        .edit-text{
            margin-top: 0;
            padding-left: 20px;
        }
    }
    .preview-image-wrap{
        max-width: 100%;
        .preview-image {
            display: block;
            max-width: 100%;
            height: 200px;
        }
    }
</style>
